﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CloudShot.Entities;
using CloudShot.Interfaces;
using CloudShot.Utils;

namespace CloudShot.Services
{
  internal class FormHotkeyService : IFormHotkeyService
  {
    private class HotkeyInfo
    {
      public Hotkey Hotkey { get; set; }
      public Action Callback { get; set; }
      public Section Section { get; set; }
    }

    private readonly Control _owner;
    private readonly List<HotkeyInfo> _registeredHotkeys = new List<HotkeyInfo>();

    public FormHotkeyService() { }

    public FormHotkeyService(Control owner)
    {
      _owner = owner;
      _owner.KeyDown += OnKeyDown;
    }

    private void OnKeyDown(object sender, KeyEventArgs e)
    {
      ProcessKey(e);
    }

    public bool ProcessKey(KeyEventArgs e)
    {
      bool handled = false;
      Hotkey pressedHotkey = new Hotkey(e.KeyCode, e.GetModifiers());

      foreach (var info in _registeredHotkeys.Where(i => i.Hotkey == pressedHotkey))
      {
        if (info.Section != null && !info.Section.Enabled)
          continue;

        info.Callback();
        handled = true;
      }

      e.Handled = handled;
      return handled;
    }

    public bool RegisterHotkey(Hotkey hotkey, EventHandler callback, Section section = null)
    {
      return RegisterHotkey(hotkey, () => callback(_owner, EventArgs.Empty), section);
    }

    public bool RegisterHotkey(Hotkey hotkey, Action callback, Section section = null)
    {
      var hkInfo = new HotkeyInfo
      {
        Hotkey = hotkey,
        Callback = callback,
        Section = section
      };

      _registeredHotkeys.Add(hkInfo);
      return true;
    }
  }

}
